package com.jumaojiang.scheduled;

import com.jumaojiang.constant.AppConfig;
import com.jumaojiang.mapper.FileResourceMapper;
import com.jumaojiang.mapper.ResourceGetTimeMapper;
import com.jumaojiang.mapper.RsVideoMapper;
import com.jumaojiang.mapper.VideoResourceMapper;
import com.jumaojiang.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.util.Calendar.*;
import static java.util.Calendar.SECOND;

/**
 * 每天0点准时更新表
 *
 * @author wuhanwei
 * @version 1.0
 * @date 2021/11/9
 */
@Service
public class ResetUserResource {

    @Autowired
    private FileResourceMapper fileResourceMapper;
    @Autowired
    private VideoResourceMapper videoResourceMapper;
    @Autowired
    private ResourceGetTimeMapper resourceGetTimeMapper;
    @Autowired
    private RsVideoMapper rsVideoMapper;
    @Autowired
    private AppConfig appConfig;

    // @Scheduled(cron = "0/10 * * * * ?")   // TODO: 十秒执行一次 详细教程 -> https://www.matools.com/cron 注意只有6个字段,教程中有7个
    @Scheduled(cron = "0 0 0 * * ?")    // 每天0点执行一次
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void everyDayReset(){
        Map<Integer, Integer> userIdMap = new HashMap<>();
        // 查询当天获取过的资源
        FileResourceExample fileResourceExample = new FileResourceExample();
        FileResourceExample.Criteria criteria = fileResourceExample.createCriteria();
        criteria.andIsOwnEqualTo(0);
        List<FileResource> fileResources = fileResourceMapper.selectByExample(fileResourceExample);
        // 添加活跃用户map
        for (FileResource fileResource : fileResources) {
            userIdMap.put(fileResource.getUserId(),fileResource.getUserId());
        }
        // 删除fileResource
        fileResourceMapper.deleteByExample(fileResourceExample);
        // 查询当天获取过的资源
        VideoResourceExample videoResourceExample = new VideoResourceExample();
        VideoResourceExample.Criteria criteria1 = videoResourceExample.createCriteria();
        criteria1.andIsOwnEqualTo(0);
        List<VideoResource> videoResources = videoResourceMapper.selectByExample(videoResourceExample);
        // 添加活跃用户map
        for (VideoResource videoResource : videoResources) {
            userIdMap.put(videoResource.getUserId(),videoResource.getUserId());
        }
        // 删除videoResource
        videoResourceMapper.deleteByExample(videoResourceExample);
        // 自增每日可获取次数和重置今日剩余获取次数
        List<ResourceGetTime> resourceGetTimes = resourceGetTimeMapper.selectByExample(null);
        for (ResourceGetTime resourceGetTime : resourceGetTimes) {
            if(userIdMap.get(resourceGetTime.getUserId()) != null){
                Integer everyDayTime = resourceGetTime.getEveryDayTime();
                // 前一天使用过, 此处自增每日可获取次数与重置今日剩余获取次数
                resourceGetTime.setEveryDayTime(everyDayTime + 1);
                resourceGetTime.setTodayTime(everyDayTime + 1); // todayTime重置为每日可获取次数
                // 更新表
                int i = resourceGetTimeMapper.updateByPrimaryKeySelective(resourceGetTime);
                if(i != 0){
                    // TODO : 自增每日可获取次数和重置今日剩余获取次数异常,推送到微信
                }
            }
        }
        // 生成脚本文件
        createscriptFile();
    }


    /**
     * 生成脚本文件
     */
    public void createscriptFile(){
        // 前一天的开始和结束时间
        Calendar cal = Calendar.getInstance();
        Date nowTime = cal.getTime();
        cal.add(Calendar.DATE,-1);
        cal.set(HOUR_OF_DAY, 0);
        cal.set(MINUTE, 0);
        cal.set(SECOND, 0);
        Date startTime = cal.getTime();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime));
        cal.set(HOUR_OF_DAY, 23);
        cal.set(MINUTE, 59);
        cal.set(SECOND, 59);
        Date endTime = cal.getTime();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime));

        RsVideoExample rsVideoExample = new RsVideoExample();
        RsVideoExample.Criteria criteria = rsVideoExample.createCriteria();
        criteria.andVideoCreateTimeGreaterThanOrEqualTo(startTime);
        criteria.andVideoCreateTimeLessThanOrEqualTo(endTime);
        List<RsVideo> rsVideos = rsVideoMapper.selectByExample(rsVideoExample);

        String savePath = appConfig.getFileSavePath();
        String saveDirName = appConfig.getFileSaveDirName();
        System.out.println("savePath: " + savePath);
        System.out.println("saveDirName: " + saveDirName);
        String saveFileName = "m3u8__" + new SimpleDateFormat("yyyy-MM-dd").format(nowTime) + "__.sh";
        String noPathSaveFileName =  "m3u8__" + new SimpleDateFormat("yyyy-MM-dd").format(nowTime) + "__no_path__.sh";
        File dir = new File(savePath + File.separator + saveDirName);
        if( !dir.exists() ){
            dir.mkdirs();
        }
        File saveFile = new File(dir, saveFileName);
        File noPathSaveFile = new File(dir, noPathSaveFileName);
        if( !saveFile.exists() ){
            try {
                saveFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if( !noPathSaveFile.exists() ){
            try {
                noPathSaveFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fileOutputStream = null;
        FileOutputStream noPathSaveFileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(saveFile);
            PrintStream ps = new PrintStream(fileOutputStream);
            noPathSaveFileOutputStream = new FileOutputStream(noPathSaveFile);
            PrintStream noPathPs = new PrintStream(noPathSaveFileOutputStream);
            for (RsVideo rsVideo : rsVideos) {
                ps.println("ffmpeg -i " + rsVideo.getVideoM3u8() + " " + savePath + File.separator +  saveDirName + File.separator +  rsVideo.getVideoName() + ".mp4 > " + savePath + File.separator +  saveDirName + File.separator +  "temp.log");
                noPathPs.println("ffmpeg -i " + rsVideo.getVideoM3u8() + " " + rsVideo.getVideoName() + ".mp4 > " +  "temp.log");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
                noPathSaveFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
